
package com.platform.modules.mall.activity;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.common.annotation.SysLog;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.RestResponse;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.ValidUtils;
import com.platform.modules.mall.entity.MallActivityEntity;
import com.platform.modules.mall.service.MallActivityService;
import com.platform.modules.mall.service.MallShopsToActivityService;
import com.platform.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;

/**
 * 日常活动Controller
 *
 * @author
 * @date 2021-08-11 16:21:47
 */
@RestController
@RequestMapping("mall/activity")
public class MallActivityController extends AbstractController {
    @Autowired
    private MallActivityService mallActivityService;
    @Autowired
    private MallShopsToActivityService shopsToActivityService;

    /**
     * 获取活动的详细信息（缓存）
     *
     * @param activityId 活动ID
     * @return RestResponse
     */
    @RequestMapping("/getDetails")
    @RequiresPermissions("mall:activity:list")
    public RestResponse getDetails(String activityId) {
        return RestResponse.success().put("data", mallActivityService.getActivityDetails(activityId, null));
    }

    /**
     * 删除活动缓存
     *
     * @param activityId 活动ID
     * @return RestResponse
     */
    @RequestMapping("/delCache")
    @RequiresPermissions("mall:activity:list")
    public RestResponse delCache(String activityId) {
        mallActivityService.delCache(activityId);
        return RestResponse.success();
    }

    /**
     * 保存活动关联的店铺ID
     *
     * @param params
     * @return RestResponse
     */
    @PostMapping("/saveShopsToActivty")
    @RequiresPermissions("mall:activity:list")
    public RestResponse saveShopsToActivty(@RequestBody Map<String, Object> params) {
        ArrayList list = (ArrayList) params.get("shopsIds");
        String activtyId = (String) params.get("activtyId");
        ValidUtils.allNotNull(activtyId, list);

        MallActivityEntity entity = mallActivityService.getById(activtyId);
        if (entity.getIsShow().equals(0)) {
            return RestResponse.error("下架状态无法操作！");
        }
        return RestResponse.success().put("list", shopsToActivityService.saveShopsToActivty(entity, list));
    }

    /**
     * 获取活动关联的店铺ID
     *
     * @param activityId 活动ID
     * @return RestResponse
     */
    @RequestMapping("/getShopsIds")
    @RequiresPermissions("mall:activity:list")
    public RestResponse getShopsIds(String activityId) {
        return RestResponse.success().put("list", shopsToActivityService.getShopsIdList(activityId));
    }

    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAll")
    @RequiresPermissions("mall:activity:list")
    public RestResponse queryAll(@RequestParam Map<String, Object> params) {
        List<MallActivityEntity> list = mallActivityService.queryAll(params);

        return RestResponse.success().put("list", list);
    }

    /**
     * 分页查询日常活动
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @GetMapping("/list")
    @RequiresPermissions("mall:activity:list")
    public RestResponse list(@RequestParam Map<String, Object> params) {
        Page page = mallActivityService.queryPage(params);

        return RestResponse.success().put("page", page);
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return RestResponse
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("mall:activity:info")
    public RestResponse info(@PathVariable("id") String id) {
        MallActivityEntity mallActivity = mallActivityService.getById(id);

        return RestResponse.success().put("activity", mallActivity);
    }

    /**
     * 新增日常活动
     *
     * @param mallActivity mallActivity
     * @return RestResponse
     */
    @SysLog("新增日常活动")
    @RequestMapping("/save")
    @RequiresPermissions("mall:activity:save")
    public RestResponse save(@RequestBody MallActivityEntity mallActivity) {
        format(mallActivity);
        mallActivityService.add(mallActivity);
        return RestResponse.success();
    }

    private void format(MallActivityEntity mallActivity) {
        if (StringUtils.isBlank(mallActivity.getActivityDate()) || StringUtils.isBlank(mallActivity.getActivityTime())) {
            // 今日秒杀使用
            throw new BusinessException("活动时间不能为空！");
        }
        try {
            LocalDate[][] dates = JSONObject.parseObject(mallActivity.getActivityDate(), LocalDate[][].class);
            LocalTime[][] times = JSONObject.parseObject(mallActivity.getActivityTime(), LocalTime[][].class);
            if (dates.length == 0 || times.length == 0) {
                throw new BusinessException("活动时间不能为空！");
            }
            // 更具开始时间排序
            dates = Arrays.stream(dates).filter(x -> x.length > 0).sorted(Comparator.comparing(x -> x[0])).toArray(LocalDate[][]::new);
            times = Arrays.stream(times).filter(x -> x.length > 0).sorted(Comparator.comparing(x -> x[0])).toArray(LocalTime[][]::new);
            mallActivity.setActivityDate(JSONObject.toJSONString(dates));
            mallActivity.setActivityTime(JSONObject.toJSONString(times));
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("活动时间解析出错");
        }
    }

    /**
     * 修改日常活动
     *
     * @param mallActivity mallActivity
     * @return RestResponse
     */
    @SysLog("修改日常活动")
    @RequestMapping("/update")
    @RequiresPermissions("mall:activity:update")
    public RestResponse update(@RequestBody MallActivityEntity mallActivity) {
        format(mallActivity);
        mallActivityService.update(mallActivity);
        mallActivityService.activityDataChange(mallActivity, null);
        return RestResponse.success();
    }

    /**
     * 根据主键删除日常活动
     *
     * @param ids ids
     * @return RestResponse
     */
    @SysLog("删除日常活动")
    @RequestMapping("/delete")
    @RequiresPermissions("mall:activity:delete")
    public RestResponse delete(@RequestBody String[] ids) {
        mallActivityService.deleteBatch(ids);
        for (String id : ids) {
            mallActivityService.activityDataChange(null, id);
        }
        return RestResponse.success();
    }
}
